import {observable, action, flow, makeObservable} from 'mobx';
import {
  login_status,
  logout as logout_api,
  user_playlist,
  personalized,
  likelist as likelistApi,
  like as likeApi,
} from '../apis';

class GlobalStore {
  @observable logined = false;
  @observable account = {};
  @observable profile = {};
  @observable likelist = [];
  @observable myplaylist = [];
  @observable recommend_playlist = [];

  constructor() {
    makeObservable(this);
  }

  @action.bound
  setLogined(logined) {
    this.logined = logined;
  }

  @action.bound
  setUserInfo(account, profile) {
    this.account = account;
    this.profile = profile;
  }

  @flow.bound
  *loadUserInfo() {
    const {data} = yield login_status();
    const {account, profile} = data;
    if (account && profile) {
      this.logined = true;
      this.account = account;
      this.profile = profile;
      this.loadLikeList();
    }
  }

  @flow.bound
  *loadLikeList() {
    if (this.account.id) {
      const {ids} = yield likelistApi(this.account.id);
      this.likelist = ids;
    }
  }

  @flow.bound
  *likeMusic(id, like) {
    if (this.logined) {
      yield likeApi(id, like);
      this.loadLikeList();
    }
  }

  @flow.bound
  *logout() {
    yield logout_api();
    this.logined = false;
    this.account = null;
    this.profile = null;
  }

  @flow.bound
  *loadMyPlaylist() {
    if (this.logined) {
      const {playlist} = yield user_playlist({uid: this.account.id});
      this.myplaylist = playlist;
    }
  }

  @flow.bound
  *loadRecommendPlaylist() {
    const {result} = yield personalized({limit: 10});
    this.recommend_playlist = result;
  }
}

export default new GlobalStore();
